package com.edvinli.filter;

import com.edvinli.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    //HttpServletRequest quest = (HttpServletRequest) servletRequest这段代码
    //
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //0. 强转对象(为获取url做准备)
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1. 获取请求uri        url全路径，uri资源路径。在实际开发中，uri就足够使用了。
        String uri = request.getRequestURI();
        log.info("uri:{}", uri);

        //2. 判断请求uri中是否包含login，如果包含，说明是登录操作，放行
        if (uri.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //3. 获取请求头中的令牌（token）
        String token = request.getHeader("token");

        //4. 判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (token == null){
            response.setStatus(401);
            log.error("令牌不存在");
            return;
        }
        //5. 解析token，如果解析失败，返回错误结果（未登录）
        try {
            //Claims claims = JwtUtils.parseJWT(token);
            Map<String, Object> claims = JwtUtils.parseJWT(token);
            log.info("jwt令牌:{}", claims);
        } catch (Exception e) {
            response.setStatus(401);
            log.error("令牌检验有误:{}",e.getMessage());
            return;
        }

        //6. 放行
        filterChain.doFilter(request, response);
    }
}
